<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Zone extends Controller
{
	private $_template_f;
	private $_lang;
	private $_bad_limit = 10;
	private $_num_view = 100;
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->_template_f = $this->config->item('template_f');
		
		$this->load->language('common', $this->_lang);
		$common_lang = $this->lang->line('common_lang');
		if(!$this->session->userdata('uname'))
		{
			$currUrl = $this->mycommon->getCurrentUrl();
			redirect(site_url('/login'). '/?url=' . urlencode($currUrl));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > -1)
			{
				show_error($common_lang['access_denied']);
				die();
			}
		}
		
		
		$this->load->model('zone/zone_model');
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Admarket' : $title;
		$header['template_f'] = $this->_template_f;
		
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
		$header['lang'] = $this->_lang;
		$header['module_name'] = 'home';
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		// load header
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}
	
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
		
		$this->load->view($this->_template_f . 'menu_view', $data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}
	
	
	function dashboard()
	{
		$date = trim($this->input->get('d'));
		$date = ($date == '') ? date('d-m-Y'): $date;
		$arrDate = explode('-', $date);
		$view_db_date = $arrDate[2] . '-' . $arrDate[1] . '-' . $arrDate[0];
				
		$this->_loadHeader('Quản lý zone');
		
		$this->_loadMenu();
		
		$data = array();
		$data = $this->zone_model->get_dashboard($view_db_date, $this->_bad_limit);
		$data['bad_limit'] = $this->_bad_limit;
		$data['view_date'] = $date;
		$percent_good = round(100*$data['total_good']/$data['total_active'],2);
		$percent_bad = round(100*$data['total_bad']/$data['total_active'],2);
		$percent_no_report = 100 - $percent_good - $percent_bad;
		
		$data['zone_chart'] = "{name:'Hiệu quả',vote:".$data['total_good'].",y:".$percent_good."}";
		$data['zone_chart'] .= ",{name:'Không hiệu quả',vote:".$data['total_bad'].",y:".$percent_bad."}";
		$data['zone_chart'] .= ",{name:'Không có report',vote:".$data['total_no_report'].",y:".$percent_no_report."}";
				
		$this->load->view($this->_template_f . 'zone/zone_dashboard_view', $data);
		
		$this->_loadFooter();
	}
	
	/*function view_type()
	{
		$type = $this->input->get('t');
		$type = ($type == 0 || $type == 1 || $type == 2 || $type == 3) ? $type : 0;
		$siteId = $this->input->get('s');
		$siteId = (is_numeric($siteId) && $siteId > -2) ? $siteId : -1;
		
		$view_date = $this->input->get('d');
		$view_date = strtotime($view_date) !== false ? $view_date : date('d-m-Y');
		$db_view_date = date('Y-m-d', strtotime($view_date));
	
		$cPage = trim($this->input->get('p'));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		
		$this->_loadHeader('Danh sách zones');
		
		$this->_loadMenu();
		
		$data = array();
		$data['type'] = $type;
		$data['siteId'] = $siteId;
		$data['cPage'] = $cPage;
		$data['view_date'] = $view_date;
		
		$data['lstSite'] = $this->zone_model->get_all_site();
		$getZoneInfo = $this->zone_model->get_list_zone($siteId, $type, $db_view_date, $this->_bad_limit, $cPage, $this->_num_view);
		$data['lstZone'] = $getZoneInfo['lstZone'];
		$data['iCount'] = $getZoneInfo['iCount'];
		$data['pCount'] = $getZoneInfo['pCount'];
		$data['numZone'] = count($data['lstZone']);
		$data['lstPaging'] = $this->mycommon->getListPaging($cPage, $data['pCount']);		
		$this->load->view($this->_template_f . 'zone/zone_view_type_view', $data);
		
		$this->_loadFooter();
	}*/
	function view_type(){
	    $export = $this->input->get('exp');
	    
		$strSiteId = trim($this->input->get('s'));
		$arrSiteId = array();
		$strRealSiteId = '';
		if($strSiteId != '')
		{
			$tmpSiteId = explode(',',$strSiteId);
			foreach($tmpSiteId as $sItem)
			{
				if(is_numeric($sItem) && $sItem > -1)
				{
					$strRealSiteId .= ($strRealSiteId != '') ? ',' . $sItem : $sItem;
					$arrSiteId[] = $sItem;
				}
			}
			$tmpSiteId = null;
		}		
		$fromdate = $this->input->get('fd');
		$fromdate = strtotime($fromdate) !== false ? $fromdate : date('d-m-Y');
		$todate = $this->input->get('td');
		$todate = strtotime($todate) !== false ? $todate : date('d-m-Y');
		    			
	    $cPage = trim($this->input->get('p'));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
	    
	    $keyword = '';
	    
	    if($export != '')
	    {
	    	if(isset($_POST['txtexp']))
	    	{
	    		$strZone = trim($_POST['txtexp']);
				if($strZone != '')
	    		{
					$lstZone = json_decode($strZone);
					$filename = "zone_report_". $fromdate . "_" . $todate;
	                header("Content-type: application/vnd.ms-excel");
	                header("Content-disposition: csv" . $fromdate . "_" . $todate . ".csv");
	                header( "Content-disposition: filename=".$filename.".csv");
	                
	                $csv_output = '';		        			
	                $csv_output .= "ID\t";
	                $csv_output .= "Tên\t";
	                $csv_output .= "Kích thước\t";
	                $csv_output .= "Website\t";
	                $csv_output .= "Total Click\t";
	                $csv_output .= "Real Click\t";
	                $csv_output .= "Click Charge\t";
	                $csv_output .= "Impressions\t";
	                $csv_output .= "CTR (%)\t";
	                $csv_output .= "\n";
	                
	                foreach($lstZone as $zone)
	                {
	                	$csv_output .= trim($zone->id) . "\t";
	                	$csv_output .= trim($zone->name) . "\t";
	                	$csv_output .= trim($zone->size) . "\t";
	                	$csv_output .= trim($zone->site) . "\t";
	                	$csv_output .= (trim($zone->tc) == '' || trim($zone->tc) == -1) ? 'N/A' . "\t" : trim($zone->tc) . "\t";
	                	$csv_output .= (trim($zone->rc) == '' || trim($zone->rc) == -1) ? 'N/A' . "\t" : trim($zone->rc) . "\t";
	                	$csv_output .= (trim($zone->cc) == '' || trim($zone->cc) == -1) ? 'N/A' . "\t" : trim($zone->cc) . "\t";
	                	$csv_output .= (trim($zone->v) == '' || trim($zone->v) == -1) ? 'N/A' . "\t" : trim($zone->v) . "\t";
	                	$csv_output .= (trim($zone->ctr) == -1) ? 'N/A' . "\t" : trim($zone->ctr) . "\t";
	                	$csv_output .= "\n";
	                }
	                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
	                exit;
	             }
	                }
	    }
	    else
	    {
			
			$this->_loadHeader('Danh sách zones');
		
			$this->_loadMenu();
			
			$data = array();
			$data['strSiteId'] = $strRealSiteId;
			$data['cPage'] = $cPage;
			$data['fromdate'] = $fromdate;
			$data['todate'] = $todate;
			$data['arrSiteId'] = $arrSiteId;
			
			
			$lstSiteByPrice = $this->zone_model->group_category_get_all($this->_lang, '');
			$lstQuickFiterSite = array();
			foreach($lstSiteByPrice as $key=>$item)
			{
				$tmp = array();
				$tmp['name'] = 'Mức giá ' . $key;
				$tmp['val'] = '';
				$tmp['lstCat'] = array();
				foreach($item as $it)
				{
					$tmpCat = array();
					$tmpCat['name'] = $it['gcat_name'];
					$tmpCat['val'] = '';
					foreach($it['lstSite'] as $sItem)
					{
						$tmpCat['val'] .= $tmpCat['val'] != '' ? ',' . $sItem['siteid'] : $sItem['siteid'];
						$tmp['val'] .= $tmp['val'] != '' ? ',' . $sItem['siteid'] : $sItem['siteid'];
					}
					$tmp['lstCat'][] = $tmpCat;
				}
				$lstQuickFiterSite[] = $tmp;
			}
			
			$data['lstQuickSiteFilter'] = $lstQuickFiterSite;
			$data['lstSite'] = $this->zone_model->get_all_site();
			$getZoneInfo = $this->zone_model->zone_get_list_zone_info($strRealSiteId, $cPage, $this->_num_view, '');
			
		 	$data['lstZone'] = array();
		 	$strZoneId = '';
		 	foreach($getZoneInfo['lstZone'] as $zItem)
		 	{
		 		$strZoneId .= ($strZoneId == '') ? $zItem['zoneid'] : ',' . $zItem['zoneid'];
		 	}
		 	$zoneReport = array();
		 	if($strZoneId != '')
		 	{
		 		$zoneReport = $this->zone_model->zone_get_report($strZoneId, date('Y-m-d', strtotime($fromdate)),  date('Y-m-d', strtotime($todate)));
	 		}
		 	
		 	$totalClick = 0;
		 	$totalRealClick = 0;
		 	$totalClickCharge = 0;
		 	$totalView = 0;
		 	foreach($getZoneInfo['lstZone'] as $zItem)
		 	{
		 		$zItem['tc'] = '';
		 		$zItem['rc'] = '';
		 		$zItem['cc'] = '';
		 		$zItem['v'] = '';
		 		$zItem['ctr'] = '';
		 		if(isset($zoneReport[$zItem['zoneid']]))
		 		{
		 			$zItem['tc'] = $zoneReport[$zItem['zoneid']]['tc'];
		 			$totalClick += (float)$zItem['tc'];
		 			$zItem['rc'] = $zoneReport[$zItem['zoneid']]['rc'];
		 			$totalRealClick += (float)$zItem['rc'];
		 			$zItem['cc'] = $zoneReport[$zItem['zoneid']]['cc'];
		 			$totalClickCharge += (float)$zItem['cc'];
		 			$zItem['v'] = $zoneReport[$zItem['zoneid']]['v'];
		 			$totalView += (float) $zItem['v'];
		 			if(trim($zItem['v'] != 'N/A') && trim($zItem['v']) != '' && $zItem['v'] > 0 && trim($zItem['rc'] != 'N/A') && trim($zItem['rc']) != '')
		 			{
		 				$zItem['ctr'] = round(($zItem['rc']/$zItem['v'])*100, 3);
		 			}
		 		}
		 		$data['lstZone'][] = $zItem;
		 	}
		 	$data['totalclick'] = $totalClick;
		 	$data['totalrealclick'] = $totalRealClick;
		 	$data['totalclickcharge'] = $totalClickCharge;
		 	$data['totalview'] = $totalView;
			$data['iCount'] = $getZoneInfo['iCount'];
			$data['pCount'] = $getZoneInfo['pCount'];
			$data['numZone'] = count($data['lstZone']);
			
			$getZoneInfo = null;
		 	$zoneReport = null;
			$this->load->view($this->_template_f . 'zone/zone_view_type_view', $data);
			
			$this->_loadFooter();
	    }
	}
	
    function zone_report()
	{
		$export = $this->input->get('exp');
	    			
		$toDate = trim($this->input->get('to'));
		$toDate = (strtotime($toDate) === false) ? date('d-m-Y') : $toDate;
		
		$fromDate = trim($this->input->get('from'));
		$fromDate = (strtotime($fromDate) === false) ? date('d-m-Y', strtotime($toDate) - (7*86400)) : $fromDate;
		
		$strZoneId = trim($this->input->get('zid'));
		$tmp = explode(',', $strZoneId);
		$arrZId = array();
		foreach($tmp as $item)
		{
			if(intval($item) > 0)
			{
				$arrZId[] = $item;
			}
		}
		$strZoneId = '';
		foreach($arrZId as $item)
		{
			$strZoneId .= $strZoneId == '' ? $item : ',' . $item;	
		}
		if($strZoneId != '')
		{
			$data = array();
			$dbFromDate = date('Y-m-d', strtotime($fromDate));
			$dbTotDate = date('Y-m-d', strtotime($toDate));
			$numZoneId = count($arrZId);
			$data['lstZone'] = $this->zone_model->zone_get_zone_info_by_list_id($strZoneId, $dbFromDate, $dbTotDate, $arrZId);
						
			if(count($data['lstZone']) > 0)
			{
				$report_data = $this->zone_model->zone_get_zone_chart_data($strZoneId, $dbFromDate, $dbTotDate, $arrZId);
				if($export != '')
	    		{
	    			$filename = "zone_report_".$fromDate."_".$toDate;
	                header("Content-type: application/vnd.ms-excel");
	                header("Content-disposition: csv" . $fromDate."_".$toDate . ".csv");
	                header( "Content-disposition: filename=".$filename.".csv");
	                
	                $csv_output = '';
	                $csv_output .= "Report from $fromDate to $toDate";
	                $csv_output .= "\n";
	                $csv_output .= "Ngày\t";
	                $csv_output .= "Zone name\t";
	                $csv_output .= "Click\t";
	                $csv_output .= "Impressions\t";
	                $csv_output .= "CTR (%)\t";
	                $csv_output .= "\n";
	                $rowDate = '';
					foreach($report_data['lstData'] as $key=>$val)
					{
						$keyDate = date('d/m/Y', strtotime($key));
						foreach($data['lstZone'] as $zItem)
						{
							if($rowDate == '' || $rowDate != $keyDate)
							{
								$csv_output .= $keyDate . "\t";
								$rowDate = $keyDate;
							}
							else
							{
								$csv_output .= "\t";
							}
							if(isset($val[$zItem['zoneid']]))
							{
								$csv_output .= $zItem['zonename'] . "\t";
								$csv_output .= $val[$zItem['zoneid']]['rc'] . "\t";
								$csv_output .= $val[$zItem['zoneid']]['v'] . "\t";
								$csv_output .= $val[$zItem['zoneid']]['ctr'] . "\t";
								$csv_output .="\n";
							}
							else
							{
								$csv_output .= $zItem['zonename'] . "\t";
								$csv_output .= "N/A\t";
								$csv_output .= "N/A\t";
								$csv_output .= "N/A\t";
								$csv_output .="\n";
							}
						}
					}
					
					$csv_output .="\n";
					$csv_output .="Dữ liệu tổng\n";
				 	$csv_output .= "Ngày\t";
	                $csv_output .= "Click\t";
	                $csv_output .= "Impressions\t";
	                $csv_output .= "CTR (%)\t";
	                $csv_output .= "\n";
					foreach($report_data['lstData'] as $key=>$val)
					{
						$tClick = 'N/A';
						$tView = 'N/A';
						$tCtr = 'N/A';
						foreach($data['lstZone'] as $zItem)
						{
							if(isset($val[$zItem['zoneid']]))
							{
								if(is_numeric($val[$zItem['zoneid']]['rc']) && $val[$zItem['zoneid']]['rc'] > 0)
								{
									$tClick = $tClick + $val[$zItem['zoneid']]['rc'];
								}
								if(is_numeric($val[$zItem['zoneid']]['v']) && $val[$zItem['zoneid']]['v'] > 0 )
								{
									$tView = $tView + $val[$zItem['zoneid']]['v'];
								}
							}
						}
						
						$tCtr = (is_numeric($tView) && is_numeric($tClick) && $tView > 0) ? round(($tClick/$tView)*100, 3) : 'N/A';
						$csv_output .= date('d/m/Y', strtotime($key)) . "\t";
						$csv_output .= $tClick . "\t";
						$csv_output .= $tView . "\t";
						$csv_output .= $tCtr . "\t";
						$csv_output .="\n";
					}
	                						                
	                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
	                exit;
				}
				else
				{
					$this->_loadHeader('Danh sách zones');
		
					$this->_loadMenu();
					
					$arrDate = $this->zone_model->zone_get_date_range($dbFromDate, $dbTotDate, 'd-m-Y');
					$numDate = count($arrDate);
					
					$clickDataView = array();
					$impDataView = array();
					$tmpIndex= 1;
					$chartStep = (count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
					
					$arrTotal = array();
					$arrClickChart = array();
					$arrViewChart = array();
					foreach($data['lstZone'] as $zItem)
					{
						$arrClickChart[$zItem['zoneid']] = array();
						$arrViewChart[$zItem['zoneid']] = array();
						for($i = 0; $i < $numDate; $i++)
						{
							$arrClickChart[$zItem['zoneid']][$i] = 0;
							$arrViewChart[$zItem['zoneid']][$i] = 0;
						}
					}
					$tClick = array();
					$tView = array();
					for($i = 0; $i < $numDate; $i++)
					{
						$tClick[$i] = 0;
						$tView[$i] = 0;
					}
					
					foreach($report_data['lstData'] as $key=>$val)
					{
						$arrTotal[$key] = array();
						$arrTotal[$key]['click'] = 'N/A';
						$arrTotal[$key]['view'] = 'N/A';
						$arrTotal[$key]['ctr'] = 'N/A';
						$index = 0;
						$keyDate = trim(date('d-m-Y', strtotime($key)));
						for($i = 0; $i < $numDate; $i++)
						{
							if(trim($arrDate[$i]) == $keyDate)
							{
								$index = $i;
								break;
							}
						}
						
						foreach($data['lstZone'] as $zItem)
						{
							if(isset($val[$zItem['zoneid']]))
							{
								if(is_numeric($val[$zItem['zoneid']]['rc']) && $val[$zItem['zoneid']]['rc'] > 0)
								{
									$arrTotal[$key]['click'] = $arrTotal[$key]['click'] + $val[$zItem['zoneid']]['rc'];
									$arrClickChart[$zItem['zoneid']][$index] = floatval($val[$zItem['zoneid']]['rc']);
								}
								else
								{
									$arrClickChart[$zItem['zoneid']][$index] = 0;
								}
								if(is_numeric($val[$zItem['zoneid']]['v']) && $val[$zItem['zoneid']]['v'] > 0 )
								{
									$arrTotal[$key]['view'] = $arrTotal[$key]['view'] + $val[$zItem['zoneid']]['v'];
									$arrViewChart[$zItem['zoneid']][$index] = floatval($val[$zItem['zoneid']]['v']);
								}
								else
								{
									$arrViewChart[$zItem['zoneid']][$index] = 0;
								}
							}
							else
							{
								$arrClickChart[$zItem['zoneid']][$index] = 0;
								$arrViewChart[$zItem['zoneid']][$index] = 0;
							}
						}
						$tClick[$index] = floatval($arrTotal[$key]['click']);
						$tView[$index] = floatval($arrTotal[$key]['view']);
						$arrTotal[$key]['ctr'] = (is_numeric($arrTotal[$key]['view']) && is_numeric($arrTotal[$key]['click']) && $arrTotal[$key]['view'] > 0) ? round(($arrTotal[$key]['click']/$arrTotal[$key]['view'])*100, 3) : 'N/A';
					}
					
					foreach($data['lstZone'] as $zone)
					{
						if($tmpIndex == 1)
						{
							$color = '#627AAD';
						}
						else if($tmpIndex == 2)
						{
							$color = '#FF9900';
						}
						else 
						{
							$a = rand(128, 255);
							$a = dechex($a);
							$b = rand(64, 255);
							$b = dechex($b);
							$c = rand(128, 255);
							$c = dechex($c);
							$color = '#' . $a.$b.$c;
						}
						
		            	$tmpChart=json_encode(array('name'=>strip_tags($zone['zonename']),'data'=> $arrClickChart[$zone['zoneid']],'color'=> $color));
	
		            	$clickDataView[] = $tmpChart;
		            	
		            	$tmpChart=json_encode(array('name'=>strip_tags($zone['zonename']),'data'=>$arrViewChart[$zone['zoneid']],'color'=> $color));
		            	
		            	$impDataView[] = $tmpChart;
		            	$tmpIndex++;
					}
					
					
					$totalClickChart = json_encode(array('name'=>'Total click','data'=> $tClick,'color'=> '#627AAD'));	
	      			$totalViewChart =json_encode(array('name'=>'Total Impressions','data'=>$tView,'color'=> '#627AAD'));
		            	
					$data['tClick'] = $totalClickChart;
					$data['tView'] = $totalViewChart;
					
					$data['clickData'] = $clickDataView;
					$data['arrTotal'] = $arrTotal;
					$data['impData'] = $impDataView;
					$data['lstData'] = $report_data['lstData'];
					$data['fromDate'] = $fromDate;
					$data['toDate'] = $toDate;
					$data['arrDate'] = $arrDate;
					$data['numZone'] = count($arrZId);
					$data['chartStep'] = $chartStep;
					$data['strZoneId'] = $strZoneId;
					$this->load->view($this->_template_f . 'zone/zone_report_view', $data);
					$this->_loadFooter();
				}
			}
			else
			{
				$this->load->view($this->_template_f . 'zone/zone_report_error_view', $data);
				$this->_loadFooter();
			}		
	            
		}
		else
		{
			$this->_loadHeader('View zone report');
		
			$this->_loadMenu();
			
			$data = array();
			
			$this->load->view($this->_template_f . 'zone/zone_report_error_view', $data);
			
			$this->_loadFooter();
		}
	}
	
    function view_delete()
    {  	
    	$siteId = $this->input->get('s');
		$siteId = (is_numeric($siteId) && $siteId > -1) ? $siteId : -1;
		
		$export = $this->input->get('exp');
			
		$fromdate = $this->input->get('fd');
		$fromdate = strtotime($fromdate) !== false ? $fromdate : date('d-m-Y');
		$todate = $this->input->get('td');
		$todate = strtotime($todate) !== false ? $todate : date('d-m-Y');
		    			
    	$cPage = trim($this->input->get('p'));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		
		if($export == 'cvs')
		{
			if(isset($_POST['txtexp']))
    		{
    			$strZone = trim($_POST['txtexp']);
				if($strZone != '')
    			{
					$lstZone = json_decode($strZone);
					$filename = "zone_delete_report_". $fromdate . "_" . $todate;
	                header("Content-type: application/vnd.ms-excel");
	                header("Content-disposition: csv" . $fromdate . "_" . $todate . ".csv");
	                header( "Content-disposition: filename=".$filename.".csv");
	                
	                $csv_output = '';		        			
	                $csv_output .= "ID\t";
	                $csv_output .= "Tên\t";
	                $csv_output .= "Kích thước\t";
	                $csv_output .= "Website\t";
	                $csv_output .= "Total Click\t";
	                $csv_output .= "Real Click\t";
	                $csv_output .= "Click Charge\t";
	                $csv_output .= "Impressions\t";
	                $csv_output .= "CTR (%)\t";
	                $csv_output .= "\n";
	                foreach($lstZone as $zone)
	                {
	                	$csv_output .= trim($zone->id) . "\t";
	                	$csv_output .= trim($zone->name) . "\t";
	                	$csv_output .= trim($zone->size) . "\t";
	                	$csv_output .= trim($zone->site) . "\t";
	                	$csv_output .= (trim($zone->tc) == '' || trim($zone->tc) == -1) ? 'N/A' . "\t" : trim($zone->tc) . "\t";
	                	$csv_output .= (trim($zone->rc) == '' || trim($zone->rc) == -1) ? 'N/A' . "\t" : trim($zone->rc) . "\t";
	                	$csv_output .= (trim($zone->cc) == '' || trim($zone->cc) == -1) ? 'N/A' . "\t" : trim($zone->cc) . "\t";
	                	$csv_output .= (trim($zone->v) == '' || trim($zone->v) == -1) ? 'N/A' . "\t" : trim($zone->v) . "\t";
	                	$csv_output .= (trim($zone->ctr) == -1) ? 'N/A' . "\t" : trim($zone->ctr) . "\t";
	                	$csv_output .= "\n";
	                }
	                print $csv = chr(255).chr(254).mb_convert_encoding($csv_output, "UTF-16LE", "UTF-8");
	                exit;
             	}
                }
		}
		else
		{
			$this->_loadHeader('Danh sách zones');
		
			$this->_loadMenu();
						 						
			$data = array();
			$data['fromdate'] = $fromdate;
			$data['todate'] = $todate;
			$data['siteId'] = $siteId;
			$data['lstSite'] = $this->zone_model->get_all_site();
								
			$getZoneInfo = $this->zone_model->zone_get_list_delete_zone($siteId, $cPage, $this->_num_view);
		 	$data['lstZone'] = array();
		 	$strZoneId = '';
		 	foreach($getZoneInfo['lstZone'] as $zItem)
		 	{
		 		$strZoneId .= ($strZoneId == '') ? $zItem['zoneid'] : ',' . $zItem['zoneid'];
		 	}
		 	
		 	$totalClick = 0;
		 	$totalRealClick = 0;
		 	$totalClickCharge = 0;
		 	$totalView = 0;
		 	$zoneReport = array();
		 	if($strZoneId != '')
		 	{
		 		$zoneReport = $this->zone_model->zone_get_report($strZoneId, date('Y-m-d', strtotime($fromdate)),  date('Y-m-d', strtotime($todate)));
	 		}
		 	foreach($getZoneInfo['lstZone'] as $zItem)
		 	{
		 		$zItem['tc'] = '';
		 		$zItem['rc'] = '';
		 		$zItem['cc'] = '';
		 		$zItem['v'] = '';
		 		$zItem['ctr'] = '';
		 		if(isset($zoneReport[$zItem['zoneid']]))
		 		{
		 			$zItem['tc'] = $zoneReport[$zItem['zoneid']]['tc'];
		 			$zItem['rc'] = $zoneReport[$zItem['zoneid']]['rc'];
		 			$zItem['cc'] = $zoneReport[$zItem['zoneid']]['cc'];
		 			$totalClick += (float)$zItem['tc'];
		 			$totalRealClick += (float)$zItem['rc'];
		 			$totalClickCharge += (float)$zItem['cc'];
		 			$zItem['v'] = $zoneReport[$zItem['zoneid']]['v'];
		 			$totalView += (float) $zItem['v'];
		 			if(trim($zItem['v'] != 'N/A') && trim($zItem['v']) != '' && $zItem['v'] > 0 && trim($zItem['rc'] != 'N/A') && trim($zItem['rc']) != '')
		 			{
		 				$zItem['ctr'] = round(($zItem['rc']/$zItem['v'])*100, 3);
		 			}
		 		}
		 		$data['lstZone'][] = $zItem;
		 	}
		 	
		 	$data['totalclick'] = $totalClick;
		 	$data['totalrealclick'] = $totalClick;
		 	$data['totalclickcharge'] = $totalClick;
		 	$data['totalview'] = $totalView;
		 	$data['cPage'] = $cPage;
			$data['iCount'] = $getZoneInfo['iCount'];
			$data['pCount'] = $getZoneInfo['pCount'];
			$data['numZone'] = count($data['lstZone']);
			
			$data['numZone'] = count($data['lstZone']);
			$this->load->view($this->_template_f . 'zone/zone_delete_view', $data);
			$this->_loadFooter();
		}
    }

    function zone_del_ajax_view_type()
    {
    	$data = array();
    	$data['right'] = '';
    	$data['login'] = '';
    	$totalClick = (float) trim($this->input->get('ttc'));
    	$totalRealClick = (float) trim($this->input->get('ttrc'));
    	$totalClickCharge = (float) trim($this->input->get('ttcc'));
    	$totalView = (float) trim($this->input->get('ttv'));
		$siteId = trim($this->input->get('s'));
		$siteId = (is_numeric($siteId) && $siteId > -1) ? $siteId : -1;
		$fromdate = $this->input->get('fd');
		$fromdate = strtotime($fromdate) !== false ? $fromdate : date('d-m-Y');
		$todate = $this->input->get('td');
		$todate = strtotime($todate) !== false ? $todate : date('d-m-Y');
		    			
		$cPage = trim($this->input->get('p'));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		
		$keyword = '';
		
		if($cPage > 1)
		{
			$dataView = array();
			$getZoneInfo = $this->zone_model->zone_get_list_delete_zone($siteId, $cPage, $this->_num_view);
			
		 	$dataView['lstZone'] = array();
		 	$strZoneId = '';
		 	foreach($getZoneInfo['lstZone'] as $zItem)
		 	{
		 		$strZoneId .= ($strZoneId == '') ? $zItem['zoneid'] : ',' . $zItem['zoneid'];
		 	}
		 	$zoneReport = array();
		 	if($strZoneId != '')
		 	{
		 		$zoneReport = $this->zone_model->zone_get_report($strZoneId, date('Y-m-d', strtotime($fromdate)),  date('Y-m-d', strtotime($todate)));
		 	}
		 	foreach($getZoneInfo['lstZone'] as $zItem)
		 	{
		 		$zItem['tc'] = '';
			 	$zItem['rc'] = '';
			 	$zItem['cc'] = '';
		 		$zItem['v'] = '';
		 		$zItem['ctr'] = '';
		 		if(isset($zoneReport[$zItem['zoneid']]))
		 		{
		 			$zItem['tc'] = $zoneReport[$zItem['zoneid']]['tc'];
		 			$zItem['rc'] = $zoneReport[$zItem['zoneid']]['rc'];
		 			$zItem['cc'] = $zoneReport[$zItem['zoneid']]['cc'];
		 			$totalClick += (float)$zItem['tc'];
		 			$totalRealClick += (float)$zItem['rc'];
		 			$totalClickCharge += (float)$zItem['cc'];
		 			
		 			$zItem['v'] = $zoneReport[$zItem['zoneid']]['v'];
		 			$totalView += (float) $zItem['v'];
		 			if(trim($zItem['v'] != 'N/A') && trim($zItem['v']) != '' && $zItem['v'] > 0 && trim($zItem['rc'] != 'N/A') && trim($zItem['rc']) != '')
		 			{
		 				$zItem['ctr'] = round(($zItem['rc']/$zItem['v'])*100, 3);
		 			}
		 		}
		 		$dataView['lstZone'][] = $zItem;
		 	}
		 	
		 	$dataView['fromdate'] = $fromdate;
		 	$dataView['todate'] = $todate;
		 	
		 	$data['totalclick'] = $totalClick;
		 	$data['totalview'] = $totalView;
		 	$data['totalctr'] = '';
		 	
		 	$data['cPage'] = $cPage;
			$data['iCount'] = $getZoneInfo['iCount'];
			$data['pCount'] = $getZoneInfo['pCount'];
			$data['numZone'] = count($dataView['lstZone']);
			
			if($cPage == $data['pCount'])
			{
				$data['totalctr'] = ($totalView > 0) ? round(($totalClick/$totalView)*100, 3) : '';
				$data['totalclick'] = number_format($data['totalclick']);
				$data['totalview'] = number_format($data['totalview']);
			}
			
			$getZoneInfo = null;
		 	$zoneReport = null;
								
			$data['data'] = $this->load->view($this->_template_f . 'zone/zone_ajax_view_type_view', $dataView, true);
		}
		echo json_encode($data);
    }
    

    
    function zone_ajax_view_type()
    {
    	$data = array();
    	$data['right'] = '';
    	$data['login'] = '';
    	
    	$totalClick = (float) trim($this->input->get('ttc'));
		$totalRealClick = (float) trim($this->input->get('ttrc'));
		$totalClickCharge = (float) trim($this->input->get('ttcc'));
		$totalView = (float) trim($this->input->get('ttv'));
		$strSiteId = trim($this->input->get('s'));
		$arrSiteId = array();
		$strRealSiteId = '';
		if($strSiteId != '')
		{
		    $tmpSiteId = explode(',',$strSiteId);
		    foreach($tmpSiteId as $sItem)
		    {
		        if(is_numeric($sItem) && $sItem > -1)
		        {
		            $strRealSiteId .= ($strRealSiteId != '') ? ',' . $sItem : $sItem;
		            $arrSiteId[] = $sItem;
		        }
		    }
		}
		$fromdate = $this->input->get('fd');
		$fromdate = strtotime($fromdate) !== false ? $fromdate : date('d-m-Y');
		$todate = $this->input->get('td');
		$todate = strtotime($todate) !== false ? $todate : date('d-m-Y');
		                
		$cPage = trim($this->input->get('p'));
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		
		$keyword = '';
		
		if($cPage > 1)
		{
		    $dataView = array();
		    $getZoneInfo = $this->zone_model->zone_get_list_zone_info($strRealSiteId, $cPage, $this->_num_view, '');
		    
		    $dataView['lstZone'] = array();
		    $strZoneId = '';
		    foreach($getZoneInfo['lstZone'] as $zItem)
		    {
		        $strZoneId .= ($strZoneId == '') ? $zItem['zoneid'] : ',' . $zItem['zoneid'];
		    }
		    
		    $zoneReport = $this->zone_model->zone_get_report($strZoneId, date('Y-m-d', strtotime($fromdate)),  date('Y-m-d', strtotime($todate)));
		    
		    foreach($getZoneInfo['lstZone'] as $zItem)
		    {
		        $zItem['tc'] = '';
		        $zItem['rc'] = '';
		        $zItem['cc'] = '';
		        $zItem['v'] = '';
		        $zItem['ctr'] = '';
		        if(isset($zoneReport[$zItem['zoneid']]))
		        {
		            $zItem['tc'] = $zoneReport[$zItem['zoneid']]['tc'];
		            $zItem['rc'] = $zoneReport[$zItem['zoneid']]['rc'];
		            $zItem['cc'] = $zoneReport[$zItem['zoneid']]['cc'];
		            $totalClick += (float)$zItem['tc'];
		            $totalRealClick += (float)$zItem['rc'];
		            $totalClickCharge += (float)$zItem['cc'];
		            $zItem['v'] = $zoneReport[$zItem['zoneid']]['v'];
		            $totalView += (float) $zItem['v'];
		            if(trim($zItem['v'] != 'N/A') && trim($zItem['v']) != '' && $zItem['v'] > 0 && trim($zItem['rc'] != 'N/A') && trim($zItem['rc']) != '')
		            {
		                $zItem['ctr'] = round(($zItem['rc']/$zItem['v'])*100, 3);
		            }
		        }
		        $dataView['lstZone'][] = $zItem;
		    }
		    
		    $dataView['fromdate'] = $fromdate;
		    $dataView['todate'] = $todate;
		    
		    $data['totalclick'] = $totalClick;
		    $data['totalrealclick'] = $totalRealClick;
		    $data['totalclickcharge'] = $totalClickCharge;
		    $data['totalview'] = $totalView;
		    $data['totalctr'] = '';
		    
		    $data['cPage'] = $cPage;
		    $data['iCount'] = $getZoneInfo['iCount'];
		    $data['pCount'] = $getZoneInfo['pCount'];
		    $data['numZone'] = count($dataView['lstZone']);
		    
		    if($cPage == $data['pCount'])
		    {
		        $data['totalctr'] = ($totalView > 0) ? round(($totalClick/$totalView)*100, 3) : '';
		        $data['totalclick'] = number_format($data['totalclick']);
		        $data['totalrealclick'] = number_format($data['totalrealclick']);
		        $data['totalclickcharge'] = number_format($data['totalclickcharge']);
		        $data['totalview'] = number_format($data['totalview']);
		    }
		    
		    $getZoneInfo = null;
		    $zoneReport = null;
		                        
		    $data['data'] = $this->load->view($this->_template_f . 'zone/zone_ajax_view_type_view', $dataView, true);
			echo json_encode($data);
		}
    }
	
	function report()
	{
		$toDate = trim($this->input->get('to'));
		$toDate = (strtotime($toDate) === false) ? date('d-m-Y') : $toDate;
		
		$fromDate = trim($this->input->get('from'));
		$fromDate = (strtotime($fromDate) === false) ? date('d-m-Y', strtotime($toDate) - (7*86400)) : $fromDate;
		
		$strZoneId = trim($this->input->get('zid'));
		$tmp = explode(',', $strZoneId);
		$arrZId = array();
		foreach($tmp as $item)
		{
			if(intval($item) > 0)
			{
				$arrZId[] = $item;
			}
		}
		$strZoneId = '';
		foreach($arrZId as $item)
		{
			$strZoneId .= $strZoneId == '' ? $item : ',' . $item;	
		}
		if($strZoneId != '')
		{
			
			$this->_loadHeader('View zone report');
		
			$this->_loadMenu();
			
			$data = array();
			$dbFromDate = date('Y-m-d', strtotime($fromDate));
			$dbTotDate = date('Y-m-d', strtotime($toDate));
			$numZoneId = count($arrZId);
			$data['lstZone'] = $this->zone_model->get_zone_info_by_list_id($strZoneId, $dbFromDate, $dbTotDate, $arrZId);
						
			if(count($data['lstZone']) > 0)
			{
				$report_data = $this->zone_model->get_zone_chart_data($strZoneId, $dbFromDate, $dbTotDate, $arrZId);
				
				$arrDate = $this->zone_model->get_date_range($dbFromDate, $dbTotDate, 'd-m-Y');
				$clickDataView = array();
				$impDataView = array();
				$tmpIndex= 1;
				$chartStep = (count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
				
				$arrClickChart = array();
				$arrViewChart = array();
				foreach($data['lstZone'] as $zItem)
				{
					$arrClickChart[$zItem['zoneid']] = array();
					$arrViewChart[$zItem['zoneid']] = array();
				}
				
				foreach($report_data['lstData'] as $key=>$val)
				{
					foreach($data['lstZone'] as $zItem)
					{
						if(isset($val[$zItem['zoneid']]))
						{
							if(is_numeric($val[$zItem['zoneid']]['rc']) && $val[$zItem['zoneid']]['rc'] > 0)
							{
								$arrClickChart[$zItem['zoneid']][] = floatval($val[$zItem['zoneid']]['rc']);
							}
							else
							{
								$arrClickChart[$zItem['zoneid']][] = 0;
							}
							if(is_numeric($val[$zItem['zoneid']]['v']) && $val[$zItem['zoneid']]['v'] > 0 )
							{
								$arrViewChart[$zItem['zoneid']][] = floatval($val[$zItem['zoneid']]['v']);
							}
							else
							{
								$arrViewChart[$zItem['zoneid']][] = 0;
							}
						}
						else
						{
							$arrClickChart[$zItem['zoneid']][] = 0;
							$arrViewChart[$zItem['zoneid']][] = 0;
						}
					}
				}
				
				foreach($data['lstZone'] as $zone)
				{
					if($tmpIndex == 1)
					{
						$color = '#627AAD';
					}
					else if($tmpIndex == 2)
					{
						$color = '#FF9900';
					}
					else 
					{
						$a = rand(128, 255);
						$a = dechex($a);
						$b = rand(64, 255);
						$b = dechex($b);
						$c = rand(128, 255);
						$c = dechex($c);
						$color = '#' . $a.$b.$c;
					}
	            	$tmpChart=json_encode(array('name'=>strip_tags($zone['zonename']),'data'=>$arrClickChart[$zone['zoneid']],'color'=> $color));

	            	$clickDataView[] = $tmpChart;
	            	
	            	$tmpChart = '';
	            	$tmpChart=json_encode(array('name'=>strip_tags($zone['zonename']),'data'=>$arrViewChart[$zone['zoneid']],'color'=> $color));
	            	
	            	$impDataView[] = $tmpChart;
	            	$tmpIndex++;
				}
				$data['clickData'] = $clickDataView;
				$data['impData'] = $impDataView;
				$data['lstData'] = $report_data['lstData'];
				$data['fromDate'] = $fromDate;
				$data['toDate'] = $toDate;
				$data['arrDate'] = $arrDate;
				$data['numZone'] = count($arrZId);
				$data['chartStep'] = $chartStep;
				$data['strZoneId'] = $strZoneId;
				$this->load->view($this->_template_f . 'zone/zone_report_view', $data);
			}
			else
			{
				$this->load->view($this->_template_f . 'zone/zone_report_error_view', $data);
			}		
            $this->_loadFooter();
		}
		else
		{
			$this->_loadHeader('View zone report');
		
			$this->_loadMenu();
			
			$data = array();
			
			$this->load->view($this->_template_f . 'zone/zone_report_error_view', $data);
			
			$this->_loadFooter();
		}
		
	}
	
	function update_status($zoneid, $status)
	{
		$zoneid = (is_numeric($zoneid) && $zoneid > 0) ? $zoneid : 0;
		$status = (is_numeric($status) && $status > 0 && ($status == 0 || $status == 1)) ? $status : -1;
		if($zoneid > 0 && $status != -1)
		{
			//$this->zone_model->update_zone_status($zoneid, $status);
			echo 'ok';
		}
		else
		{
			echo 'error';
		}
	}
	
	
	/*function view_delete()
	{
		$siteId = $this->input->get('s');
		$siteId = (is_numeric($siteId) && $siteId > 0) ? $siteId : 0;
				
		$this->_loadHeader('Danh sách zones không sử dụng');
		
		$this->_loadMenu();
		
		$data = array();
		$data['siteId'] = $siteId;
		$data['lstSite'] = $this->zone_model->get_all_site();
		
		$data['lstZone'] = $this->zone_model->get_list_delete_zone($siteId);
		$data['numZone'] = count($data['lstZone']);
		
		$this->load->view($this->_template_f . 'zone/zone_delete_view', $data);
		
		$this->_loadFooter();
	}*/
}